package com.guxingke.typecho4j.widget.provider.content;

import java.util.List;

import javax.servlet.ServletContext;

import com.guxingke.typecho4j.Typecho4j;
import com.guxingke.typecho4j.util.Archive;
import com.guxingke.typecho4j.widget.WidgetProvider;
import com.guxingke.typecho4j.widget.provider.ContentBaseWidget;
import com.jfinal.core.Controller;

/**
 * 侧栏归档文章组件
 * 
 * @author guxingke
 * */
public class ArchivePostsWidget extends ContentBaseWidget implements
		WidgetProvider {
	private List<Archive> archives;

	/**
	 * applicationContext,便于向application作用域中添加数据
	 * */
	private ServletContext servletContext;

	@Override
	public boolean init() {
		initLogger();

		this.servletContext = Typecho4j.typecho4j().getServletContext();

		if (constants.isShowArchive()) {
			archives = getArchives();
			servletContext.setAttribute("archives", archives);
		}

		return true;
	}

	@Override
	public void excute(Controller controller) {
		if (constants.isShowArchive()) {
			if (servletContext.getAttribute("archives") == null) {
				servletContext.setAttribute("archives",
						archives);
			}
		} else {
			if (servletContext.getAttribute("archives") != null) {
				servletContext.removeAttribute("archives");
			}
		}
	}

	@Override
	public void refresh() {
		if (constants.isShowArchive()) {
			archives = getArchives();
		} else {
			archives = null;
		}
	}
}
